package com.phonegap.gwt.camera.client.impl;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.phonegap.gwt.camera.client.Camera;
import com.phonegap.gwt.camera.client.CameraCallback;
import com.phonegap.gwt.camera.client.CameraOptions;
import com.phonegap.gwt.camera.client.PictureSourceType;
public class CameraImpl {

	  public native boolean isSupported() /*-{
	    return !!$wnd.navigator.camera;
	  }-*/;
	  
	  
	  public native Camera getCamera() /*-{
	    return $wnd.navigator.camera;
	  }-*/;
	  
	  
	  public void getPictureFromCamera(Camera camera,
		      CameraCallback callback) {
		  CameraOptions options = CameraOptions.create();
		  options.setSourceType(PictureSourceType.CAMERA);
		  options.setQuality(10);
		  getPicture(camera, callback, options);
		  }

	  public void getPictureFromLibrary(Camera camera,
		      CameraCallback callback) {
		  CameraOptions options = CameraOptions.create();
		  options.setQuality(10);
		  options.setSourceType(PictureSourceType.PHOTO_LIBRARY);
		  getPicture(camera, callback, options);
		  } 
	  public void getPicture(Camera camera,
			  CameraCallback callback, CameraOptions options) {
		    _getPicture(camera, callback, options);
		  }
	  
	  
	  protected native void _getPicture(Camera camera,
		      CameraCallback callback, CameraOptions options) /*-{
		    camera.getPicture(
		      function(picture) {
		        @com.phonegap.gwt.camera.client.impl.CameraImpl::handleSuccess(Lcom/phonegap/gwt/camera/client/CameraCallback;Ljava/lang/String;) (callback, picture);
		      },
		      function(error) {
		        @com.phonegap.gwt.camera.client.impl.CameraImpl::handleError(Lcom/phonegap/gwt/camera/client/CameraCallback;Ljava/lang/String;) (callback, error);
		      },
		      options
		    );
		  }-*/;
	  
	  
	  
	  protected static final void handleSuccess(CameraCallback callback,
		      String picture) {
		    UncaughtExceptionHandler ueh = GWT.getUncaughtExceptionHandler();
		    if (ueh != null) {
		      try {
		        callback.onSuccess(picture);
		      } catch (Throwable t) {
		        ueh.onUncaughtException(t);
		      }
		    } else {
		      callback.onSuccess(picture);
		    }
		  }

		  /*
		   * Helper method for the getCurrentPosition() / watchPosition() methods
		   */
		  protected static final void handleError(CameraCallback callback,
		      String error) {
		    UncaughtExceptionHandler ueh = GWT.getUncaughtExceptionHandler();
		    if (ueh != null) {
		      try {
		        callback.onFailure(error);
		      } catch (Throwable t) {
		        ueh.onUncaughtException(t);
		      }
		    } else {
		      callback.onFailure(error);
		    }
		  }
		  
}
